﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.Practices.EnterpriseLibrary.Validation;

using Ample.Model;

public partial class Admin_Product_ViewProduct : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && string.IsNullOrEmpty(Request.QueryString["ID"]))
        {
           dvProduct.ChangeMode(DetailsViewMode.Insert);
        }
    }

    protected void ProductDS_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        if (e.InputParameters.Count > 0 && e.InputParameters[0] == null)
            e.InputParameters[0] = newprodId;
    }

    int newprodId = -1;
    protected void ProductDS_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
    {   
        if (e.ReturnValue != null)
            newprodId = Convert.ToInt32(e.ReturnValue);
    }


    protected void ProductDS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        if (e.InputParameters.Count > 0 && e.InputParameters[0] != null)
        {
            Product prod = (Product) e.InputParameters[0];

            Validator<Product> validator = ValidationFactory.CreateValidator<Product>("DefaultRuleSet");
            ValidationResults results = validator.Validate(prod);

            System.Text.StringBuilder builder = new StringBuilder();
            // get validation results
            if (!results.IsValid)
            {
                builder.Append("<b>Validation Errors:</b>:<br />");
                foreach (ValidationResult result in results)
                {
                    builder.Append(String.Format("- <b>{0}</b><br />", result.Message));
                    //builder.Append(String.Format("&nbsp; (Key: {0}, ", result.Key.ToString()));
                    //builder.Append(String.Format("Tag: {0}, ", result.Tag));
                    //builder.Append(String.Format("Target: {0})<br />", result.Target.ToString()));
                }

                lblResult.Visible = true;
                lblResult.Text = builder.ToString();
                e.Cancel = true;
                
            }
        }
    }

    protected void dvProduct_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        if (e.AffectedRows == 0)
            e.KeepInInsertMode = true;
    }
}
